<?php
namespace Home\Controller;
use Think\Controller;
class TemplateController extends CommonController
{

	public function _initialize()
	{
		// parent::_initialize();

		# 新订单通知
		$this->order = '1HszWdSAurE6gijedEEMSzjUVYxEfqHscbExSb0j2y8';//正式
		// $this->order = 'gka_cD2QvD4nsj2moeGcOQIh8ZV45xYbksys-IeBWOI';//测试
		$this->signorder = 'Y6QCQPZRQoJhcyB16OimKKTx5EqgPmqX2BnM_gKKE7c';//测试正式同一个

		# 订单消息通知-订单取消成功
		$this->cancel = 'Eg6TM5UK9XhKfE0DTEFcyRk_DpPEfmt-OwlkJfMNJqQ';//正式
		// $this->cancel = '3U3qFMLeAFKZr5v24cQF-nu3NZZNmL0H5hOXUavoQNs';//测试
		$this->signcancel = 'VlOI0tyy1Ay0bMruF7QMlMiuZ_iMwJealeeOz1AkSJo';//测试

		# 抢单失败通知
		$this->fail = 'Xk_vbrRvz3BWCLTv269_-KEEROlEcjmerX8hYU_Eoto';//正式
		// $this->fail = 'kswbXgcn1iwvq_kZ6FQKCm1xQvqOoD6drNg6TkKtCzc';//测试

		# 抢单成功通知
		$this->success = 'sEclfFNMKYMOWlyoOz1TBnqUZ5qv2XSluzwnVxUDoME';//正式
		// $this->success = 'EaKJyOO7YXaYWSSacXHsdrGkG50hoSD2JMzP_DwZTLk';//测试
		$this->signsuccess = 'wZXiBrsBXo6bXB3OSs9epVTDqyuj8gW0euanqS5x4Js';//测试正式同一个

		# 订单即将超时提醒
		$this->delay = 'wn8k2o-YoE6pgnzVr47-RbZ1ao_dQ8UPWVK--yVCEEg';//正式
		// $this->delay = '7vACWyuJl3GGc90vPx9n2m6-d5lYb8C_ulvOIv8pQSg';//测试
		$this->signdelay = '7_O01AMbFrN4kOjRJLkmuGwjTbliqQ_yXI5lRZhy89Y';//测试正式同一个

		# 客户评价通知-评价订单
		$this->score = '9xcqywk5zI_rWc6GQebbCL9Zj5rFCyq0Io5-PLVRhqE';//正式
		// $this->score = '1msrk83zw-PRloW0UIfEUTnBazaHwWhUtBuchynWVeg';//测试
		$this->signscore = 'UVUadk0n_70OCkXf-6ZEaPNj6OcvAwfW1bx30QVv5DM';//测试正式同一个

		# 客户评价通知-驳回订单
		$this->reject = '9xcqywk5zI_rWc6GQebbCL9Zj5rFCyq0Io5-PLVRhqE';//正式
		// $this->reject = '1msrk83zw-PRloW0UIfEUTnBazaHwWhUtBuchynWVeg';//测试
		$this->signreject = 'UVUadk0n_70OCkXf-6ZEaPNj6OcvAwfW1bx30QVv5DM';//测试正式同一个

		# 订单处理超时提醒
		$this->outtime = 'g0nCxG0j_G5gqKjjB5RDrIekBoRK9mY_hqiRZAHbxMo';//正式
		// $this->outtime = 'AiplamtM3wQMAqCVFq4p0THRQmmHZp4t6mClpNhHZkk';//测试
		$this->signouttime = 'GMzigaUcj9CNYcHTx__mp-sopCeoaCOAWYR-x_Ehx2E';//测试正式同一个

		# 到账通知
		$this->account = 'XN30UI8ysgPSJdxJqQtRlEVjvoyKDORa1hoWe8Xn0sI';//正式
		// $this->account = 'rWQGWSNDypAGlpZV9T0KCXbt-Yef1xXLGQXvZe2xahQ';//测试
		$this->signaccount = 'rdR_gGWLtLB_Hn3Krso-FWykhQT1hWVcvN5A2iFt-m0';//测试正式同一个

	}

/**
* 下单时给主播发送通知
* @param $user      用户信息
* @param $order     订单信息
* @param $snatch_time     抢单时限
* @param $GetAccessToken      获取token
* @param $GetSingAccessToken      获取签约token
*/
public function sendorderMessage($user,$order,$snatch_time,$GetAccessToken){
	$nowtime = time();
	if (date("Y-m-d",$order['deliver_time']+$order['pay_time']) == date("Y-m-d",$nowtime)) {
		$day = "今日";
	}else{
		$day = "明日";
	}
	$plantime = "剩余".ceil(($order['deliver_time'])/60)."分钟(".$day.date("H:i",$order['deliver_time']+$order['pay_time'])."前)";
	$message = "请收到提示".ceil($snatch_time/60)."分钟内抢单,前五名优选中标";
	$chose = "";
	$bgmprice = 0;
	if ($order['sub_type']==3 || $order['requirement']==3 || $order['bgm_id']!=0) {
		$pricemessage = "(基础".($order['price']+0)."元";
		if ($order['sub_type']==3) {
			if ($order['requirement']==2) {
				$pricemessage = "(基础".((($order['price']+$order['increase_price'])-(($order['price']+$order['increase_price'])/3))-$order['increase_price'])."元";
				$pricemessage .= "+自选".(($order['price']+$order['increase_price'])/3)."元";
			}else{
				$pricemessage = "(基础".($order['price']-($order['price']/3))."元";
				$pricemessage .= "+自选".($order['price']/3)."元";
			}
			$chose = "自选";
			$message = "请收到提示".ceil($snatch_time/60)."分钟内抢单,客户进行选择";
		}
		if ($order['requirement']==3) {
			$pricemessage .= "+加急".($order['increase_price']+0)."元";
		}
		if ($order['bgm_id']!=0) {
			$pricemessage .= "+背景音10元";
			$bgmprice = 10;
		}
		$pricemessage .= ")";
	}
	if ($order['type'] != 3) {
		switch ($order['requirement']) {
			case '0':
				$first = "你有一笔签约订单,点击确认处理";
				$orderType = "签约订单";
				$message = "请尽快确认处理";
				break;
			case '1':
				$first = "有一个".($order['price']+$bgmprice)."元订单待抢单".$pricemessage;
				$orderType = "实时订单";
				break;
			case '3':
				$first = "有一个".($order['price']+$bgmprice+$order['increase_price'])."元订单待抢单".$pricemessage;
				$orderType = "加急订单";
				break;
			case '2':
				$first = "有一个".($order['price']+$bgmprice)."元订单待抢单".$pricemessage;
				$orderType = "预约订单";
				break;
			default:
				$first = "有一个".($order['price']+$bgmprice)."元订单待抢单".$pricemessage;
				$orderType = "实时订单";
				break;
		}
	}else{
		$first = "你有一笔派发订单,点击确认处理";
		$orderType = "派发订单";
		$message = "请尽快确认处理";
	}
	$title = mb_strlen($order['title']) > 9 ? mb_substr($order['title'],0,7, 'utf-8').'...':$order['title'];
	$orderItemData = $order['words']."字 | ".$title;
	$number = $order['id'];
	$customerInfo = "自媒体 - ".$order['media_name'];
	$remark = $message;
	if ($order['type'] != 1 && $user['openid2']) {
		$AccessToken = $this->GetSingAccessToken();
		$data['template_id'] = $this->signorder;
		$data['touser'] = $user['openid2'];
	}else{
		$AccessToken = $GetAccessToken;
		$data['template_id'] = $this->order;
		$data['touser'] = $user['openid'];
	}
	$data['AccessTokenurl'] = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$AccessToken;
	$time = date('Y/m/d H:i:s',time());
	$data['url'] = "http://".C("H5_URL").".heardtech.com/html/order-content.html?oid=".$order['id'].'&token='.$user['token'].'&uuid='.$user['uuid'];
	$data['data']['first']['value'] = $first;
	$data['data']['first']['color'] = '#FF0000';
	$data['data']['tradeDateTime']['value'] = $plantime;
	$data['data']['tradeDateTime']['color'] = '#173177';
	$data['data']['orderType']['value'] = $chose.$orderType;
	$data['data']['orderType']['color'] = '#173177';
	$data['data']['customerInfo']['value'] = $customerInfo;
	$data['data']['customerInfo']['color'] = '#173177';
	$data['data']['orderItemName']['value'] = "标题";
	$data['data']['orderItemName']['color'] = '#000000';
	$data['data']['orderItemData']['value'] = $orderItemData;
	$data['data']['orderItemData']['color'] = '#173177';
	$data['data']['remark']['value'] = $remark;
	$data['data']['remark']['color'] = '#173177';
	return $data;
}
// 获取微信AccessToken
public function GetAccessToken()
{
	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C("AppID").'&secret='.C("AppSecret");
	$data = json_decode(do_curl($url),TRUE);
	return $data['access_token'];
}
public function GetSingAccessToken()
{
	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C("SignAppID").'&secret='.C("SignAppSecret");
	$data = json_decode(do_curl($url),TRUE);
	return $data['access_token'];
}
	/**
	 * 抢单模版消息调用api
	 * @param int $oid 订单id
	 * @param int $hands_map 出手人集合
	 */
	public function template_order_api($order,$memberlist)
	{
		foreach ($memberlist as $user) {
			$orderurl = "";
			$AccessToken = $this->GetAccessToken();
			if ($order['user_id'] == $user['uuid']) {
				$templateid['success'] = $this->success;
				# 如果不是实时单 进行了签约主播认证
				if ($order['type'] != 1 && $user['openid2']) {
					$user['openid'] = $user['openid2'];
					$AccessToken = $this->GetSingAccessToken();
					$templateid['success'] = $this->signsuccess;
				}
				# 自选单不带链接
				if ($order['sub_type'] != 3 && $order['requirement'] != 3) {
					$orderurl = "http://".C("H5_URL").".heardtech.com/html/cancle-order.html?oid=".$order['id']."&token=".$user['token']."&uuid=".$user['uuid'];
				}
				$this->template_group($order,$user['openid'],$user['token'],1,$AccessToken,$templateid,$orderurl);
			}else{
				$orderurl = "http://".C("H5_URL").".heardtech.com/html/order-content.html?oid=".$order['id'].'&token='.$user['token'].'&uuid='.$user['uuid'];
				$templateid['fail'] = $this->fail;
				$this->template_group($order,$user['openid'],$user['token'],2,$AccessToken,$templateid,$orderurl);
			}
		}
	}


	# 模版消息分组
	public function template_group($order,$openid,$token,$type=1,$access_token,$templateid,$orderurl="")
	{
		$data['touser'] = $openid;
		# 如果有链接加入url
		if ($orderurl) {
			$data['url'] = $orderurl;
		}
		# 我是抢单成功的
		if ($type == 1) {
			$data['template_id'] = $templateid['success'];
			if ($order['type'] == 1) {
				# 我是实时的
				$member = M('member')->where(array('uuid'=>$order['user_id']))->find();
				$data['data']['first']['value'] = $order['words'] .'字 | ' . $order['title'];
				$data['data']['first']['color'] = '#000000';
				$data['data']['keyword1']['value'] = date('Y-m-d H:i',time());
				$data['data']['keyword1']['color'] = '#000000';
				$data['data']['keyword2']['value'] = $member['nickname'];
				$data['data']['keyword2']['color'] = '#000000';
				$data['data']['remark']['value']  =  "请在" . date('H:i',$order['pay_time'] + $order['deliver_time']) ."前登录PC端上传音频\n未及时交付系统将暂停发单";
				$data['data']['remark']['color'] = '#FF0000';
			}else{
				# 我是签约的
				$data['data']['first']['value'] = '接单成功!';
				$data['data']['first']['color'] = '#FF0000';
				$data['data']['keyword1']['value'] = $order['id'];
				$data['data']['keyword1']['color'] = '#000000';
				$data['data']['keyword2']['value'] = date('Y-m-d H:i',time());
				$data['data']['keyword2']['color'] = '#000000';
				$data['data']['remark']['value'] = "请在" . date('H:i',$order['pay_time'] + $order['deliver_time'])  ."前登录PC端上传音频";
				$data['data']['remark']['color'] = '#FF0000';
			}
		}
		# 我是抢单失败的
		if ($type == 2) {
			$data['template_id'] = $templateid['fail'];
			$data['data']['keyword1']['value'] = $order['words'] .'字 | ' . $order['title'];
			$data['data']['keyword2']['value'] = date('Y-m-d H:i',time());
			if ($order['sub_type'] != 3) {
				$data['data']['first']['value'] = '很遗憾,你被一位信用分更高的主播击败';
				$data['data']['remark']['value'] = "我们已经为你提升抢单概率,再接再厉\n未选中也有红包拿,点击详情领取";
			}else{
				$data['data']['first']['value'] = '很遗憾,用户已选择其他主播';
				$data['data']['remark']['value'] = "未选中也有红包拿,点击详情领取";
			}
			$data['data']['remark']['color'] = '#FF0000';
		}
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		$this->template_curl($url,$data);
	}


/**
* 给主播发送通知
* @param $uuid 		用户id
* @param $type 		类型  1取消   2提醒   3验收通过  4验收未通过  5订单超时
* @param $order 	订单信息
* @param $data 		参数
*/
public function ordersendmessage($uuid,$type,$order,$data)
{
	$user = M('member m')
						->join('__WECHAT__ w ON m.uuid = w.uuid')
						->where("m.uuid = $uuid")
						->field('m.uuid,m.score,m.nickname,w.token,w.openid,w.openid2')
						->find();
	if ($order['sub_type'] == 3) {
		$chose = "自选";
	}else{
		$chose = "";
	}
	switch ($order['requirement']) {
		case '1':
			$ordertype = "实时";
			break;
		case '2':
			$ordertype = "预约";
			break;
		case '3':
			$ordertype = "加急";
			break;
	}
	if ($order['type'] == 2) {
		$ordertype = "签约";
	}
	switch ($type) {
		case '1':
			if ($order['type'] == 2) {
				$message['first'] = "改派成功通知";
				$message['keyword1'] = "改派成功,您的订单已经被系统重新派发.\n提示:多次改派将导致无法接单,请谨慎.\n您的信用分-".$data['scorenum'].",目前信用分为".($user['score'])."分.";
				$message['keyword2'] = date('Y/m/d H:i:s',time())."(信息下达)";
			}else{
				$message['first'] = "取消成功通知";
				$message['keyword1'] = "取消成功,您的订单已经被系统重新派发.\n提示:多次取消将导致无法接单,请谨慎.\n您的信用分-".$data['scorenum'].",目前信用分为".($user['score'])."分.";
				$message['keyword2'] = date('Y/m/d H:i:s',time())."(信息下达)";
			}
			break;
		case '2':
			$message['first'] = "距订单交付时间仅剩20分钟";
			$message['firstcolor'] = '#FF0000';
			$message['keyword1'] = $chose.$ordertype."订单";
			$message['keyword2'] = $order['id'];
			$message['keyword3'] = $user['nickname'];
			$message['keyword4'] = "只能申请1次延时30分钟交付,点击详情申请";
			if ($order['requirement']==3) {
				$message['keyword4'] = "加急订单不能延时,请尽快交付";
			}
			$message['remark'] = "无法交付将导致系统暂停发单";
			$message['remarkcolor'] = '#FF0000';
			if ($order['requirement'] != 3) {
				$orderurl = "http://".C("H5_URL").".heardtech.com/html/cancle-order.html?oid=".$order['id']."&token=".$user['token']."&uuid=".$order['user_id'];
			}
			break;
		case '3':
			$message['first'] = "音频已验收完成";
			$message['keyword1'] = $order['media_name'];
			$message['keyword2'] = date('Y-m-d H:i',time());
			$message['keyword3'] = $data['scorestar']."星";
			$message['keyword4'] = $data['scoremessage'];
			if ($data['scorenum'] == 0) {
				$message['remark'] = "您的信用分已满,请继续保持良好的交付习惯!";
			}else{
				$message['remark'] = "您的信用分+".$data['scorenum'].",目前信用分为".($user['score'])."分.";
			}
			break;
		case '4':
			$delay_time = ($order['pay_time']+$order['deliver_time']+$order['delay_time']) - time();
			$message['first'] = "音频已被驳回";
			$message['keyword1'] = $order['media_name'];
			$message['keyword2'] = date('Y-m-d H:i',time());
			$message['keyword3'] = "无";
			$message['keyword4'] = $data['scoremessage'];
			$message['remark'] = "请在".ceil($delay_time/60)."分钟内提交";
			break;
		case '5':
			$message['first'] = "由于超时未交付,系统将暂停发单,扣除".$data['scorenum']."信用值";
			$message['firstcolor'] = '#FF0000';
			$message['keyword1'] = $chose.$ordertype."订单";
			$message['keyword2'] = $order['id'];
			$message['keyword3'] = date('Y-m-d H:i',time());
			$orderurl = "http://".C("H5_URL").".heardtech.com/html/delivery-timeout.html?uuid=".$order['user_id']."&oid=".$order['id'];
			break;
		case '6':
			$message['first'] = "订单已结算(".$order['id'].")";
			$message['keyword1'] = $order['media_name'];
			$message['keyword3'] = date('Y-m-d H:i',time());
			if ($data['price'] == 0 && $order['type'] == 2) {
				$message['keyword2'] = "累计时间已发放";
			}else{
				$message['keyword2'] = $data['price']."元";
				$message['remark'] = "已发放至钱包";
			}


			break;
	}
	 return $this->getorderMessage($type,$user,$order,$message,$orderurl);
}

public function getorderMessage($type,$user,$order,$message,$orderurl){
	if ($order['type'] == 2 && $user['openid2']) {
		$AccessToken = $this->GetSingAccessToken();
		$data['touser'] = $user['openid2'];
		switch ($type) {
			case '1':$data['template_id'] = $this->signcancel;break;
			case '2':$data['template_id'] = $this->signdelay;break;
			case '3':$data['template_id'] = $this->signscore;break;
			case '4':$data['template_id'] = $this->signreject;break;
			case '5':$data['template_id'] = $this->signouttime;break;
			case '6':$data['template_id'] = $this->signaccount;break;
		}
	}else{
		$AccessToken = $this->GetAccessToken();
		$data['touser'] = $user['openid'];
		switch ($type) {
			case '1':$data['template_id'] = $this->cancel;break;
			case '2':$data['template_id'] = $this->delay;break;
			case '3':$data['template_id'] = $this->score;break;
			case '4':$data['template_id'] = $this->reject;break;
			case '5':$data['template_id'] = $this->outtime;break;
			case '6':$data['template_id'] = $this->account;break;
		}
	}
	$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$AccessToken;
	if ($orderurl) {
		$data['url'] = $orderurl;
	}
	$data['data']['first']['value'] = $message['first'];
	$data['data']['first']['color'] = $message['firstcolor']?$message['firstcolor']:'#000000';
	$data['data']['keyword1']['value'] = $message['keyword1'];
	$data['data']['keyword1']['color'] = '#000000';
	$data['data']['keyword2']['value'] = $message['keyword2'];
	$data['data']['keyword2']['color'] = '#000000';
	if ($message['keyword3']) {
		$data['data']['keyword3']['value'] = $message['keyword3'];
		$data['data']['keyword3']['color'] = '#000000';
	}
	if ($message['keyword4']) {
		$data['data']['keyword4']['value'] = $message['keyword4'];
		$data['data']['keyword4']['color'] = '#000000';
	}
	if ($message['remark']) {
		$data['data']['remark']['value'] = $message['remark'];
		$data['data']['remark']['color'] = $message['remarkcolor']?$message['remarkcolor']:'#000000';
	}
	return $this->template_curl($url,$data);
}
	# 模版消息发送
	public function template_curl($url,$data)
	{
		$curl = curl_init($url);
		$header = array();
		$header[] = 'Content-Type: application/x-www-form-urlencoded';
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data));
		$response = curl_exec($curl);
		curl_close($curl);
		return json_decode($response);
	}
/*##################################################################*/
}